﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Collections;
using System.Configuration;

namespace RSSReader
{
    [XmlRoot("DropboxData", Namespace = "DropboxData", IsNullable = false)]
    public class DropboxData
    {
        public string DropboxFilename { get; set; }

        public RSSItems ProcessDropboxData()
        {
            List<string> log = new List<string>();
            string dummy;

            RSSItems items = new RSSItems();

            string[] lines = File.ReadAllLines(DropboxFilename);
            if (lines.Length > 0)
            {
                File.Delete(DropboxFilename);

                foreach (string line in lines)
                {
                    if (!line.Contains("Done - "))
                    {
                        RSSItem item = new RSSItem(line, DateTime.Now, "");

                        string saaPath = ConfigurationSettings.AppSettings.Get("RapidSearcher");
                        string command = saaPath + "RapidSearcher.exe";
                        string parameters = "\"" + line + "\" false ";
                        log.Add("Running: " + command + " " + parameters);
                        int ret = Utils.RunShell(command, parameters, out dummy);
                        if (ret == 0)
                        {
                            log.Add("Adding from dropbox succeeded: " + dummy);
                            File.AppendAllText(DropboxFilename, line + ": Done - added to download manager " + dummy + "\r\n");
                            item.State = AddState.FoundAndAdded;
                        }
                        else
                        {
                            log.Add("Adding from dropbox failed: " + dummy);
                            File.AppendAllText(DropboxFilename, line + ": Done - did not find a match " + dummy + "\r\n");
                            item.State = AddState.NotFound;
                        }

                        items.Add(item);
                    }
                    else
                    {
                        File.AppendAllText(DropboxFilename, line);
                    }
                }
            }

            StreamWriter sw = new StreamWriter("RssReaderLog.txt", true);
            foreach (string line in log)
                sw.WriteLine(line);
            sw.Close();

            return items;
        }
    }
}
